var request = require("../../utils/request.js");
var app = getApp();
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		username: '1715925168',
		password: '123456',
		result: false,
		avatar: null
	},

	onLoad: function () {
		var that = this
		that.setData({
			avatar: wx.getStorageSync('imageBaseUrl') + 'logo.jpg'
		})
	},

	/**
	 * 失去焦点获取用户名 对用户名做校验
	 */
	blurUserName: function (e) {
		const that = this;
		let username = e.detail.value;
		if (username == '') {
			wx.showToast({
				title: '用户名不能为空',
				icon: 'none',
				duration: 1000
			});
		} else if (username.length < 10) {
			wx.showToast({
				title: '请检查用户名长度',
				icon: 'none',
				duration: 1000
			});
		} else {
			this.data.result = true;
			var loginName = {
				"loginName": that.data.username
			}
			// 头像获取
			request.get('/selectAvatar', loginName, function (res) {
				if (res.code == 200) {
					var avarar = wx.getStorageSync('baseUrl') + res.data
					res.data != '' ? that.setData({
						avatar: avarar
					}) : that.data.avatar;
				}
			});
		}
	},
	login: function () {
		var that = this
		if (this.data.password == '') {
			wx.showToast({
				title: '密码不能为空',
				icon: 'none',
				duration: 1000
			})
			this.data.result = false;
		}
		if (this.data.result) {
			request.post('/login', this.data, function (res) {
				if (res.code == 200) {
					var schoolUser = res.data.schoolUser;
					//设置默认头像
					if (schoolUser.avatar == "") {
						schoolUser.avatar = that.data.avatar
					}
					//进行token的存储
					//这里的token随便写的,就是个唯一标识
					wx.setStorageSync("userInfo", schoolUser);
					wx.setStorageSync("token", res.data.token);
					wx.showLoading({
						title: '加载中',
					});
					setTimeout(function () {
						wx.hideLoading()
					}, 2000);
					//跳转页面
					wx.switchTab({
						url: '/pages/index/index'
					})
				} else {
					wx.showToast({
						title: res.message,
						icon: 'none',
						duration: 1000
					});
					return false;
				}
			});
		} else {
			wx.showToast({
				title: '请输入正确的用户名和密码',
				icon: 'none',
				duration: 1000
			})
		}
	}
})